import { Op } from "sequelize"
import BookDb from "../model/BookDB.js"

let fn_List = async ctx => {
  let keyword = ctx.request.query.keyword
  let where = null
  if(keyword) {
    where = {
      [Op.or] : {
        BookName : {
          [Op.like] : `%${keyword}%`
        },
        author : {
          [Op.like] : `%${keyword}%`
        }
      }
    }
  }
  ctx.body = await BookDb.findAll({where})
}

let fn_getOneDate = async ctx => {
  let id = ctx.request.params.id
//  await BookDb.findByPk(id)
  ctx.body=await BookDb.findByPk(id)
}

let fn_Add = async ctx => {
  let data = ctx.request.body
  console.log(data);
  await BookDb.create(data)
  ctx.body = '添加成功'
}

let fn_Update = async ctx => {
  let id = ctx.request.params.id
  let data = ctx.request.body //修改内容
  await BookDb.update(data,{where:{id}})
  ctx.body = '修改成功'
}

let fn_Delet = async ctx => {
  let id = ctx.request.params.id
  await BookDb.destroy({where:{id}})
  ctx.body = '删除成功'
}

export default [
  {
    method : 'get',
    url : '/bookList',
    fn : fn_List
  },
  {
    method : 'get',
    url : '/bookList/:id',
    fn : fn_getOneDate
  },
  {
    method : 'post',
    url : '/bookList',
    fn : fn_Add
  },
  {
    method : 'put',
    url : '/bookList/:id',
    fn : fn_Update
  },
  {
    method : 'delete',
    url : '/bookList/:id',
    fn : fn_Delet
  }
]